package setting

import (
	"../common"
	"../web"
	"strings"
)

type SetComputerObj struct {
	common.BaseHandler
}

func (self *SetComputerObj) Prepare() {
	lines := *common.FetchAllRowsPtr(
		`SELECT LINE 
           FROM SFC_LINE(NOLOCK) 
          ORDER BY LINE`,
		self.Usr.Conn, new(common.LineName))

	stations := *common.FetchAllRowsPtr(
		`SELECT STATION, '' 
           FROM SFC_STATION(NOLOCK) 
          ORDER BY STATION`,
		self.Usr.Conn, new(common.Station))

	computer := strings.TrimSpace(strings.Split(self.Ctx.Request.RemoteAddr, ":")[0])
	self.TmplData["computer"] = computer
	self.TmplData["lines"] = lines
	self.TmplData["stations"] = stations

	currset := *common.FetchOneRowPtr(
		`SELECT STATION, LINE 
		   FROM SFC_COMPUTER(NOLOCK) 
		  WHERE COMPUTER=?`,
		self.Usr.Conn, new(common.Computer), computer)
	self.TmplData["line"] = currset.(common.Computer).Line
	self.TmplData["station"] = currset.(common.Computer).Station
}

func (self *SetComputerObj) ParameterCheck() bool {
	c_line := self.Ctx.Params["prodline"]
	c_stat := self.Ctx.Params["stat"]
	computer := self.TmplData["computer"].(string)
	if computer == "" {
		self.TmplData["error"] = common.GetText(self.Lang,
			"Can't get the computer's name, please contact admin.")
		return false
	}
	if c_line == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please select the Line.")
		return false
	}
	if c_stat == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please select the Station.")
		return false
	}

	self.Sqlparas = append(self.Sqlparas, computer)
	self.Sqlparas = append(self.Sqlparas, c_line)
	self.Sqlparas = append(self.Sqlparas, c_stat)
	self.Sqlparas = append(self.Sqlparas, self.Usr.Username)
	self.Flashparas = []interface{}{strings.ToUpper(computer)}

	return true
}

func (self *SetComputerObj) SqlExecute() bool {
	spRtnData := *common.FetchOneRowPtr(
		`sp_SetComputer ?, ?, ?, ?`,
		self.Usr.Conn, new(common.SPReturn), self.Sqlparas...)
	if spRtnData.(common.SPReturn).Flag > 0 {
		self.TmplData["error"] = common.GetTextSP(self.Lang, spRtnData)
		return false
	}
	self.TmplData["line"] = self.Sqlparas[1]
	self.TmplData["station"] = self.Sqlparas[2]
	return true
}

func ComputerSetHandler(ctx *web.Context) {
	self := new(SetComputerObj)
	self.Ctx = ctx
	self.Url = "/setcomputer"
	self.Html = "setcomputer.html"
	self.Rightlist = []string{"setcomputer"}
	self.Flashstr = "Set Computer: [ %v ] finished."
	self.Do(self)
}
